<template>
    <div class="common-layout">
        <el-container>
            <el-header style="border-style: groove;border-width: 0px;margin-bottom: 12px;">
                <el-card>
                    <div style="display:flex;justify-content:flex-end;gap:8px;">
                        <el-button @click="handleClose">关闭</el-button>
                        <el-button type="primary" @click="save" :loading="saving">保存</el-button>
                    </div>
                </el-card>
            </el-header>
            <el-main>
                <el-card style="margin-bottom:12px;">
                    <div style="font-weight:600;margin-bottom:12px;">供应商信息</div>
                    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="供应商编码" prop="supplierCode">
                                    <el-input v-model="form.supplierCode" placeholder="自动或手动录入" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="供应商名称" prop="supplierName">
                                    <el-input v-model="form.supplierName" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="所属行业" prop="industryId">
                                    <el-select v-model="form.industryId" placeholder="请选择">
                                        <el-option v-for="it in industryList" :key="it.industryId"
                                            :label="it.industryName" :value="it.industryId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="供应商分类" prop="supplierTypeId">
                                    <el-select v-model="form.supplierTypeId" placeholder="请选择">
                                        <el-option v-for="it in supplierTypeList" :key="it.supplierTypeId"
                                            :label="it.supplierTypeName" :value="it.supplierTypeId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="联系人" prop="contact">
                                    <el-input v-model="form.contact" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="联系电话" prop="contactNumber">
                                    <el-input v-model="form.contactNumber" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="电子邮箱" prop="supplierEmail">
                                    <el-input v-model="form.supplierEmail" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="进货部门" prop="organizationId">
                                    <el-select v-model="form.organizationId" placeholder="请选择">
                                        <el-option v-for="it in organizationList" :key="it.organizationId"
                                            :label="it.organizationName" :value="it.organizationId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="进货负责人" prop="userId">
                                    <el-select v-model="form.userId" placeholder="请选择">
                                        <el-option v-for="it in userList" :key="it.userId" :label="it.userName"
                                            :value="it.userId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="状态" prop="supplierStatus">
                                    <el-radio-group v-model="form.supplierStatus">
                                        <el-radio :label="0">启用</el-radio>
                                        <el-radio :label="1">停用</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="供应商地址" prop="supplierAddress">
                                    <el-input v-model="form.supplierAddress" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="备注" prop="supplierNote">
                                    <el-input v-model="form.supplierNote" type="textarea" :rows="3" maxlength="500"
                                        show-word-limit />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-card>

                <el-card style="margin-bottom:12px;">
                    <div style="font-weight:600;margin-bottom:12px;">财务信息</div>
                    <el-form :model="form" label-width="120px">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="账户名称" prop="financeName">
                                    <el-input v-model="form.financeName" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="纳税人识别号" prop="taxpayerNumber">
                                    <el-input v-model="form.taxpayerNumber" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="银行账户" prop="bankAccount">
                                    <el-input v-model="form.bankAccount" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="开户银行" prop="accountBank">
                                    <el-input v-model="form.accountBank" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="开户行地址" prop="bankAddress">
                                    <el-input v-model="form.bankAddress" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-card>

                <el-card>
                    <div style="font-weight:600;margin-bottom:12px;">上传附件</div>
                    <el-upload :action="uploadAction" :headers="uploadHeaders" :file-list="fileList" list-type="text">
                        <el-button>上传</el-button>
                        <template #tip>
                            <div style="color:#999;">仅示例：可上传doc、pdf、rar等，单个文件不超过200MB</div>
                        </template>
                    </el-upload>
                </el-card>
            </el-main>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance } from 'element-plus'
import myaxios from '@/http/MyAxios'
import moment from 'moment'

const route = useRoute()
const router = useRouter()

const formRef = ref<FormInstance>()

const form = reactive({
    supplierId: '' as any,
    supplierCode: '',
    supplierName: '',
    industryId: '' as any,
    supplierTypeId: '' as any,
    contact: '',
    contactNumber: '',
    supplierEmail: '',
    organizationId: '' as any,
    userId: '' as any,
    supplierStatus: 0,
    supplierAddress: '',
    supplierNote: '',
    financeId: '' as any,
    financeName: '',
    taxpayerNumber: '',
    bankAccount: '',
    accountBank: '',
    bankAddress: '',
    // 操作信息
    createor: '',
    createrTime: '',
})

const rules = {
    supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
    industryId: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
    supplierTypeId: [{ required: true, message: '请选择供应商分类', trigger: 'change' }],
}

interface IndustryItem { industryId: number | string; industryName: string }
interface SupplierTypeItem { supplierTypeId: number | string; supplierTypeName: string }
interface OrganizationItem { organizationId: number | string; organizationName: string }
interface UserItem { userId: number | string; userName: string }

const industryList = ref<IndustryItem[]>([])
const supplierTypeList = ref<SupplierTypeItem[]>([])
const organizationList = ref<OrganizationItem[]>([])
const userList = ref<UserItem[]>([])

const uploadAction = ref('api/Supplier/UploadFile')
const uploadHeaders = ref({})
const fileList = ref<Array<{ name: string; url: string }>>([])

const isRootDictionary = (item: any) =>
    !item.parentId || item.parentId === 0 || item.parentId === '0' || item.parentId === null

const matchDictionary = (item: any, names: string[], codes: string[]) => {
    const name = (item.dictionaryName || '').toLowerCase()
    const code = (item.dictionaryCode || '').toLowerCase()
    return names.some(n => name === n.toLowerCase() || name.includes(n.toLowerCase())) ||
        codes.some(c => code === c.toLowerCase())
}

const findDictionaryParentId = async (nameCandidates: string[], codeCandidates: string[]) => {
    const params = { Pageindex: 1, PageSize: 1000 }
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryList', { params })
        const list = res.data?.data?.data || []
        const found = list.find((item: any) => isRootDictionary(item) && matchDictionary(item, nameCandidates, codeCandidates))
        if (found?.dictionaryId) return found.dictionaryId
    } catch (error) {
        console.warn('获取字典列表失败', error)
    }

    for (const name of nameCandidates) {
        try {
            const res = await myaxios.get('/api/Dictionary/GetDictionaryList', {
                params: { DictionaryName: name, Pageindex: 1, PageSize: 200 }
            })
            const list = res.data?.data?.data || []
            const found = list.find((item: any) => isRootDictionary(item))
            if (found?.dictionaryId) return found.dictionaryId
        } catch (error) {
            console.warn(`按名称 ${name} 获取字典失败`, error)
        }
    }
    return null
}

const fetchDictionaryChildren = async (parentId: string | number | null) => {
    if (!parentId) return []
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryChildren', {
            params: { ParentId: parentId, Pageindex: 1, PageSize: 1000 }
        })
        return res.data?.data?.data || []
    } catch (error) {
        console.warn('获取字典子项失败', error)
        return []
    }
}

const loadIndustryList = async () => {
    const parentId = await findDictionaryParentId(['所属行业', '行业'], ['industry'])
    const children = await fetchDictionaryChildren(parentId)
    industryList.value = children.map((item: any) => ({
        industryId: item.dictionaryId,
        industryName: item.dictionaryName
    }))
}

const loadSupplierTypeList = async () => {
    const parentId = await findDictionaryParentId(['供应商分类', '供应商类型'], ['suppliertype', 'supplier_type'])
    const children = await fetchDictionaryChildren(parentId)
    supplierTypeList.value = children.map((item: any) => ({
        supplierTypeId: item.dictionaryId,
        supplierTypeName: item.dictionaryName
    }))
}

const loadOrganizationList = () => {
    myaxios.get('api/Supplier/GetOrganization').then(res => {
        organizationList.value = res.data.data || []
    }).catch(err => {
        console.error('获取部门列表失败', err)
        organizationList.value = []
    })
}

const loadUserList = () => {
    myaxios.get('api/Supplier/GetUser').then(res => {
        userList.value = res.data.data || []
    }).catch(err => {
        console.error('获取负责人列表失败', err)
        userList.value = []
    })
}

const loadDetail = () => {
    const id = route.query.supplierId || route.params.supplierId
    if (!id) {
        ElMessage.error('缺少supplierId')
        return
    }
    myaxios.get('/api/Supplier/GetSupplierById', { params: { supplierId: id } }).then(res => {
        const d = res?.data?.data
        if (!d) return
        form.supplierId = d.supplierId
        form.supplierCode = d.supplierCode
        form.supplierName = d.supplierName
        form.industryId = d.industryId
        form.supplierTypeId = d.supplierTypeId
        form.contact = d.contact
        form.contactNumber = d.contactNumber
        form.supplierEmail = d.supplierEmail
        form.organizationId = d.organizationId
        form.userId = d.userId
        form.supplierStatus = d.supplierStatus
        form.supplierAddress = d.supplierAddress
        form.supplierNote = d.supplierNote
        form.financeId = d.financeId
        form.financeName = d.financeName
        form.taxpayerNumber = d.taxpayerNumber
        form.bankAccount = d.bankAccount
        form.accountBank = d.accountBank
        form.bankAddress = d.bankAddress
    })
}

const saving = ref(false)
const save = () => {
    formRef.value?.validate(async (valid) => {
        if (!valid) return
        try {
            saving.value = true
            // 自动设置操作人和操作时间 - 从后端获取真实姓名
            let currentUser = localStorage.getItem('username') || ''
            try {
                const res = await myaxios.get('/api/User/GetMyProfile')
                const droot: any = res?.data ?? {}
                const d: any = (droot?.data && Object.keys(droot).length <= 3) ? (droot.data || {}) : droot
                if (d) {
                    // 优先使用真实姓名，其次用户名
                    currentUser = d.userName || d.realName || d.nickname || currentUser
                    // 更新localStorage以便后续使用
                    if (currentUser) {
                        localStorage.setItem('username', currentUser)
                    }
                }
            } catch (error) {
                console.warn('获取当前用户信息失败，使用本地存储的值:', error)
            }
            const currentTime = moment().format('YYYY-MM-DD HH:mm:ss')
            
            // 更新表单数据中的操作人和操作时间
            form.createor = currentUser
            form.createrTime = currentTime
            
            const payload = {
                supplierId: Number(form.supplierId),
                supplierCode: form.supplierCode,
                supplierName: form.supplierName,
                industryId: Number(form.industryId),
                supplierTypeId: Number(form.supplierTypeId),
                contact: form.contact,
                contactNumber: form.contactNumber,
                supplierEmail: form.supplierEmail,
                organizationId: Number(form.organizationId),
                userId: Number(form.userId),
                supplierStatus: Number(form.supplierStatus),
                supplierAddress: form.supplierAddress,
                supplierNote: form.supplierNote,
                financeId: Number(form.financeId),
                financeName: form.financeName,
                taxpayerNumber: form.taxpayerNumber,
                bankAccount: form.bankAccount,
                accountBank: form.accountBank,
                bankAddress: form.bankAddress,
                createor: currentUser,
                createrTime: currentTime,
            }
            const res = await myaxios.put('/api/Supplier/UpdateSupplierWithFinance', payload)
            if (res.data.code === 200) {
                ElMessage.success(res.data.message || '保存成功')
                router.back()
            } else {
                ElMessage.error(res.data.message || '保存失败')
            }
        } catch (e: any) {
            ElMessage.error(e?.message || '保存失败')
        } finally {
            saving.value = false
        }
    })
}

const handleClose = () => { router.back() }

onMounted(() => {
    loadIndustryList()
    loadSupplierTypeList()
    loadOrganizationList()
    loadUserList()
    loadDetail()
})
</script>

<style scoped></style>
